package com.probox.common.entity.service.platfom.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.probox.common.core.constant.HttpStatus;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.core.utils.money.MoneyUtils;
import com.probox.common.core.web.domain.AjaxResult;
import com.probox.common.entity.domain.customer.CustomerInfo;
import com.probox.common.entity.domain.order.OrderInfoItem;
import com.probox.common.entity.mapper.order.OrderInfoMapper;
import com.probox.common.entity.service.customer.ICustomerInfoService;
import com.probox.common.entity.vo.WeCom.WeComCustomerArchivesVo;
import com.probox.common.entity.vo.customerService.CustomerServiceBuyRecordVo;
import com.probox.common.entity.vo.statistics.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional
public class StatisticsService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private ICustomerInfoService customerInfoService;


    /**
     * 销售统计报表
     *
     * @param vo
     * @return
     */
    public AjaxResult selectProductSale(ProductSaleVo vo) {
        AjaxResult ajaxResult = new AjaxResult();

        if (StringUtils.isNotEmpty(vo.getPayMethod())){
            String[] pays = vo.getPayMethod().split(",");
            List<String> list = new ArrayList<>();
            for (String p:pays) {
                list.add(p);
            }
            vo.setPayMethodList(list);
        }

        if (StringUtils.isEmpty(vo.getStartTime()) || StringUtils.isEmpty(vo.getEndTime())){
            List<ProductSaleVo> productSaleVos = new ArrayList<>();
            ajaxResult.put("rows", productSaleVos);
            ajaxResult.put("code", HttpStatus.SUCCESS);
            ajaxResult.put("msg", "查询成功");
            ajaxResult.put("total", new PageInfo(productSaleVos).getTotal());
            ProductSaleVo data = new ProductSaleVo();
            data.setAmount(0L);
            data.setNumber(0L);
            ajaxResult.put("data", data);
            return ajaxResult;
        }
        if (vo.getStoreId() == null && !SecurityUtils.getUsername().equalsIgnoreCase("admin")){
            List<ProductSaleVo> productSaleVos = new ArrayList<>();
            ajaxResult.put("rows", productSaleVos);
            ajaxResult.put("code", HttpStatus.SUCCESS);
            ajaxResult.put("msg", "查询成功");
            ajaxResult.put("total", new PageInfo(productSaleVos).getTotal());
            ProductSaleVo data = new ProductSaleVo();
            data.setAmount(0L);
            data.setNumber(0L);
            ajaxResult.put("data", data);
            return ajaxResult;
        }

        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<ProductSaleVo> productSaleVos = orderInfoMapper.selectProductSale(vo);
        ajaxResult.put("rows", productSaleVos);
        ajaxResult.put("code", HttpStatus.SUCCESS);
        ajaxResult.put("msg", "查询成功");
        ajaxResult.put("total", new PageInfo(productSaleVos).getTotal());
        ajaxResult.put("data", orderInfoMapper.selectOrderCountAndAmount(vo));
        return ajaxResult;
    }


    public List<ProductSaleVo> selectProductSaleExport(ProductSaleVo vo) {
        return orderInfoMapper.selectProductSale(vo);
    }

    /**
     * 根据类型和id查询对应的订单数据
     *
     * @param vo
     * @return
     */
    public List<OrderInfoItem> selectItemByProUidAndType(ProductSaleVo vo) {
        return orderInfoMapper.selectItemByProUidAndType(vo);
    }


    /**
     * 销售统计报表
     *
     * @param vo
     * @return
     */
    public AjaxResult selectCardConsumptionSale(CardConsumptionSaleVo vo) {
        AjaxResult ajaxResult = new AjaxResult();
        if (StringUtils.isNotEmpty(vo.getStartTime())){
            vo.setStartTime(vo.getStartTime().substring(0,7));
        }
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<CardConsumptionSaleVo> productSaleVos = orderInfoMapper.selectCardConsumptionSale(vo);
        ajaxResult.put("rows", productSaleVos);
        ajaxResult.put("code", HttpStatus.SUCCESS);
        ajaxResult.put("msg", "查询成功");
        ajaxResult.put("total", new PageInfo(productSaleVos).getTotal());
        ajaxResult.put("data", orderInfoMapper.selectCardConsumptionCountAndAmount(vo));
        return ajaxResult;
    }


    public List<CardConsumptionSaleVo> selectCardConsumptionSaleExport(CardConsumptionSaleVo vo) {
        if (StringUtils.isNotEmpty(vo.getStartTime())){
            vo.setStartTime(vo.getStartTime().substring(0,7));
        }
        return orderInfoMapper.selectCardConsumptionSale(vo);
    }

    public List<SubscribeDetailVo> selectCardConsumptionSaleDetail(CardConsumptionSaleVo vo) {
        if (StringUtils.isNotEmpty(vo.getStartTime())){
            vo.setStartTime(vo.getStartTime().substring(0,7));
        }
        return orderInfoMapper.selectCardConsumptionSaleDetail(vo);
    }




    /**
     * 耗卡报表详情
     *
     * @param vo
     * @return
     */
    public List<CardConsumptionSaleDetailVo> selectCardConsumptionSaleByProUidAndType(CardConsumptionSaleDetailVo vo) {
        return orderInfoMapper.selectCardConsumptionSaleByProUidAndType(vo);
    }

    /**
     * 门店销售报表
     *
     * @param vo
     * @return
     */
    public List<StoreManagementVo> selectStoreManagementVo(StoreManagementVo vo) {
        if (StringUtils.isNotEmpty(vo.getStartTime())){
            vo.setStartTime(vo.getStartTime().substring(0,7));
        }
        return orderInfoMapper.selectStoreManagementVo(vo);
    }
    public List<OrderInfoItem> getStaticOrder(StoreManagementVo vo) {
        return orderInfoMapper.getStaticOrder(vo.getStoreId(),vo.getTime());
    }


    public List<?> getStoreManagementDetail(StoreManagementVo vo) {
        /**
         * type 有
         * people 体验人数 美团 抖音
         * item 具体项目 美团护理 抖音护理
         */
        WeComCustomerArchivesVo archivesVo = new WeComCustomerArchivesVo();
        archivesVo.setTime(vo.getTime());
        archivesVo.setSourcePlatform(vo.getSourcePlatform());
        archivesVo.setStoreId(vo.getStoreId());
        archivesVo.setSubscribeId(vo.getSubscribeId());

        return new ArrayList<>();
    }

    /**
     * 储值统计报表
     *
     * @return
     */
    public List<StoreRechargeVo> selectStoreRechargeVo(StoreRechargeVo vo) {
        return orderInfoMapper.selectStoreRechargeVo(vo);
    }

    /**
     * 美容师报表
     *
     * @param vo
     * @return
     */
    public AjaxResult selectBeauticianRankingVo(BeauticianRankingVo vo) {
        AjaxResult ajaxResult = new AjaxResult();
        BeauticianRankingVo beauticianRankingVo = null;
        List<BeauticianRankingVo> beauticianRankingVos = null;
        if (vo.getStoreId() == null) {
            beauticianRankingVo = new BeauticianRankingVo();
            beauticianRankingVo.setAmount(0L);
            beauticianRankingVo.setNumber(0);
            beauticianRankingVos = new ArrayList<>();
        } else {
            BeauticianRankingVo beauticianRankingVo2 = orderInfoMapper.selectBeauticianRankingVoCount(vo);
            beauticianRankingVo = beauticianRankingVo2;
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            beauticianRankingVos = orderInfoMapper.selectBeauticianRankingVo(vo);
            if (CollectionUtil.isNotEmpty(beauticianRankingVos)) {
                beauticianRankingVos.forEach(vos -> {
                    vos.setAmountProportion(MoneyUtils.changeStrPercentage(vos.getAmount(), beauticianRankingVo2.getAmount()));
                    vos.setNumberProportion(MoneyUtils.changeStrPercentage(Convert.toLong(vos.getNumber()), Convert.toLong(beauticianRankingVo2.getNumber())));
//                if(ObjectUtil.isNotEmpty(vos.getNumberProportion())){
//                    vos.setNumberProportionStr(MoneyUtils.changeStrPercentage(vos.getNumberProportion()));
//                }
//                if(ObjectUtil.isNotEmpty(vos.getAmountProportion())){
//                    vos.setAmountProportionStr(MoneyUtils.changeStrPercentage(vos.getAmountProportion()));
//                }
                });
            }
        }
        ajaxResult.put("rows", beauticianRankingVos);
        ajaxResult.put("code", HttpStatus.SUCCESS);
        ajaxResult.put("msg", "查询成功");
        ajaxResult.put("total", new PageInfo(beauticianRankingVos).getTotal());
        ajaxResult.put("data", beauticianRankingVo);
        return ajaxResult;
    }


    /**
     * 美容师报表明细
     *
     * @param vo
     * @return
     */
    public List<CardConsumptionSaleDetailVo> selectBeauticianRankingDetail(BeauticianRankingVo vo) {
        return orderInfoMapper.selectBeauticianRankingDetail(vo);
    }

    /**
     * 注册转换
     *
     * @param vo
     * @return
     */
    public List<RegistrationConversionVo> selectRegistrationConversion(RegistrationConversionVo vo) {
        return orderInfoMapper.selectRegistrationConversion(vo);
    }


    public List<CustomerInfo> getCustomerInfoDetailType(String time,String type,Long storeId) {
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
        if("activeMembers".equals(type)){

            queryWrapper.last(" where phone in ( SELECT\n" +
                    "         DISTINCT a.mobile \n" +
                    "        FROM\n" +
                    "        (\n" +
                    "\t\t\t\tSELECT mobile from (\n" +
                    "        SELECT\n" +
                    "        cssr.subscribe_id,\n" +
                    "        cssr.store_id,\n" +
                    "        cssr.mobile,\n" +
                    "        cssr.subscribe_date\n" +
                    "        FROM\n" +
                    "        customer_service_subscribe_record cssr\n" +
                    "        LEFT JOIN customer_service_subscribe_record_detail cssrd ON cssrd.subscribe_id = cssr.subscribe_id\n" +
                    "        WHERE\n" +
                    "        cssr.DATA_STATUS = 1\n" +
                    "        AND cssr.service_status = 3\n" +
                    "        AND cssrd.data_status = 1\n" +
                    "        AND cssr.customer_id IS NOT NULL\n" +
                    "        and  cssr.store_id = "+storeId+"\n" +
                    "        AND cssr.subscribe_date LIKE CONCAT( '"+time+"', '%' ) "+
                    "        GROUP BY\n" +
                    "        cssr.subscribe_id\n" +
                    "        HAVING\n" +
                    "        count( cssr.subscribe_id ) > 1 ) d\n" +
                    "\t\t\t\tUNION\n" +
                    "        SELECT        \n" +
                    "        cssr.mobile        \n" +
                    "        FROM\n" +
                    "        customer_service_subscribe_record cssr\n" +
                    "        WHERE\n" +
                    "        cssr.DATA_STATUS = 1\n" +
                    "        AND cssr.service_status = 3\n" +
                    "        AND cssr.customer_id IS NOT NULL\n" + " and  cssr.store_id = "+storeId+"\n" +
                    "        AND cssr.subscribe_date LIKE CONCAT( '"+time+"', '%' ) "+
                    "        GROUP BY\n" +
                    "        cssr.mobile\n" +
                    "        HAVING\n" +
                    "        count( 1 ) > 1\n" +
                    "        ) a )");

        }else if("appletStransformationCount".equals(type)){
            /*
            queryWrapper.last(" where customer_uid in (SELECT\n" +
                    "\t\t a.customer_uid \n" +
                    "\tFROM\n" +
                    "\t\tcustomer_info a\n" +
                    "\t\tLEFT JOIN customer_service_subscribe_record b ON a.CUSTOMER_UID = b.CUSTOMER_ID \n" +
                    "\tWHERE\n" +
                    "\t\ta.CREATE_TIME LIKE CONCAT(  '"+time+"', '%' ) \n" +
                    "\t\tAND b.DATA_STATUS = 1 \n" +
                    "\t\tAND b.service_status = 3 \n" +
                    "\t\tAND b.store_id = "+storeId+" \n" +
                    "\t\tAND b.subscribe_date LIKE CONCAT( '"+time+"', '%' ) )");
            */
            queryWrapper.select("  ci.customer_uid,ci.customer_no,ci.CUSTOMER_NAME,ci.HEAD_IMAGE,ci.sex,ci.phone,cssr.subscribe_date as create_time  \n" );
            queryWrapper.last("  ci LEFT JOIN customer_service_subscribe_record cssr on ci.customer_uid=cssr.customer_id where cssr.DATA_STATUS = 1 and cssr.service_amount>1 \n" +
                    "        AND cssr.service_status = 3 \n" +
                    "        and cssr.store_id = "+storeId+"\n" +
                    "        AND cssr.subscribe_date LIKE CONCAT( '"+time+"', '%' ) " +
                    "        AND ci.create_time LIKE CONCAT( '"+time+"', '%' ) "
            );
        }else if("nursingCount".equals(type)){
            queryWrapper.last(" where phone in ( \tSELECT\n" +
                    "\t\t DISTINCT  mobile \n" +
                    "\tFROM\n" +
                    "\t\tcustomer_service_subscribe_record \n" +
                    "\tWHERE\n" +
                    "\t\tDATA_STATUS = 1 \n" +
                    "\t\tAND service_status = 3 \n" +
                    "\t\tAND store_id ="+storeId+" \n" +
                    "\t\tAND subscribe_date LIKE CONCAT( '"+time+"', '%' ) )");
        }else if("projectOverlay".equals(type)){
            queryWrapper.select("  ci.customer_uid,ci.customer_no,ci.CUSTOMER_NAME,ci.HEAD_IMAGE,ci.sex,ci.phone,cssr.subscribe_date as create_time  \n" );
            queryWrapper.last("  ci LEFT JOIN customer_service_subscribe_record cssr on ci.customer_uid=cssr.customer_id where cssr.DATA_STATUS = 1 and cssr.service_amount>1 \n" +
                    "        AND cssr.service_status = 3 \n" +
                    "        and cssr.store_id = "+storeId+"\n" +
                    "        AND cssr.subscribe_date LIKE CONCAT( '"+time+"', '%' ) "
            );
            /*
            queryWrapper.last("where phone in ( SELECT\n" +
                    "        cssr.mobile\t\t\t\t\n" +
                    "        FROM\n" +
                    "        customer_service_subscribe_record cssr\n" +
                    "        LEFT JOIN customer_service_subscribe_record_detail cssrd ON cssrd.subscribe_id = cssr.subscribe_id\n" +
                    "        WHERE\n" +
                    "        cssr.DATA_STATUS = 1\n" +
                    "        AND cssr.service_status = 3\n" +
                    "        AND cssrd.data_status = 1\n" +
                    "        and cssr.store_id = "+storeId+"\n" +
                    "        AND cssr.subscribe_date LIKE CONCAT( '"+time+"', '%' ) "+
                    "        GROUP BY\n" +
                    "        cssr.mobile\n" +
                    "        HAVING\n" +
                    "        count( 1 ) > 1 )");*/

        }else if ("customer".equals(type)){
            //到店会员数
            /*
            queryWrapper.last(" where phone in ( SELECT\n" +
                    "        cssr.mobile" +
                    "        FROM\n" +
                    "        customer_service_subscribe_record cssr\n" +
                    "        LEFT JOIN customer_service_subscribe_record_detail cssrd ON cssrd.subscribe_id = cssr.subscribe_id\n" +
                    "        WHERE\n" +
                    "        cssr.DATA_STATUS = 1\n" +
                    "        AND cssr.service_status = 3\n" +
                    "        AND cssrd.data_status = 1\n" +
                    "        and cssr.store_id = "+storeId+"\n" +
                    "        AND cssr.subscribe_date LIKE CONCAT( '"+time+"', '%' )) "
                    );*/
            queryWrapper.select("  ci.customer_uid,ci.customer_no,ci.CUSTOMER_NAME,ci.HEAD_IMAGE,ci.sex,ci.phone,cssr.subscribe_date as create_time  \n" );
            queryWrapper.last("  ci LEFT JOIN customer_service_subscribe_record cssr on ci.customer_uid=cssr.customer_id where cssr.DATA_STATUS = 1 \n" +
                    "        AND cssr.service_status = 3\n" +
                    "        and cssr.store_id = "+storeId+"\n" +
                    "        AND cssr.subscribe_date LIKE CONCAT( '"+time+"', '%' ) "
            );
        }


        return customerInfoService.list(queryWrapper);
    }


    /**
     * 根据时间查询注册人数
     *
     * @param time
     * @return
     */
    public List<CustomerInfo> getCustomerInfoDetail(String time) {
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.last(" where create_time like concat('" + time + "','%') ");
        return customerInfoService.list(queryWrapper);
    }




    public List<CustomerInfo> getCustomerInfoOrderDetail(String time) {
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.last(" where  customer_uid in (select customer_uid from order_info where order_status =1 " +
                " and pay_status =1 and pay_time like concat('" + time + "','%')   )  ");
        return customerInfoService.list(queryWrapper);
    }


    /**
     * 耗卡渠道报表
     *
     * @param vo
     * @return
     */
    public AjaxResult selectChannelVo(BeauticianRankingVo vo) {
        AjaxResult ajaxResult = new AjaxResult();
        ChannelVo channelVo = orderInfoMapper.selectChannelVoStatistics(vo);
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<ChannelVo> channelVos = orderInfoMapper.selectChannelVo(vo);
        if (CollectionUtil.isNotEmpty(channelVos)) {
            channelVos.forEach(vos -> {
                vos.setAmountProportion(MoneyUtils.changeStrPercentage(vos.getAmount(), channelVo.getAmount()));
                vos.setNumberProportion(MoneyUtils.changeStrPercentage(Convert.toLong(vos.getNumber()), Convert.toLong(channelVo.getNumber())));
                vos.setPeopleNumberProportion(MoneyUtils.changeStrPercentage(Convert.toLong(vos.getPeopleNumber()), Convert.toLong(channelVo.getPeopleNumber())));

            });
        }
        ajaxResult.put("rows", channelVos);
        ajaxResult.put("code", HttpStatus.SUCCESS);
        ajaxResult.put("msg", "查询成功");
        ajaxResult.put("total", new PageInfo(channelVos).getTotal());
        ajaxResult.put("data", channelVo);
        return ajaxResult;
    }

    /**
     * 其他数据报表 项目叠加
     *
     * @param vo
     * @return
     */
    public AjaxResult selectOtherVo(OtherVo vo) {
        AjaxResult ajaxResult = new AjaxResult();
        List<OtherVo> otherVos = orderInfoMapper.listOtherVo(vo);
        HashMap map = new HashMap();
        map.put("data", otherVos);
        ajaxResult.put("rows", map);
        ajaxResult.put("code", HttpStatus.SUCCESS);
        ajaxResult.put("msg", "查询成功");
        ajaxResult.put("data", orderInfoMapper.selectOtherVo(vo));
        return ajaxResult;
    }

    public AjaxResult selectOtherVoTimes(OtherVo vo) {
        AjaxResult ajaxResult = new AjaxResult();
        List<OtherVo> otherVos = orderInfoMapper.listOtherVoTimes(vo);
        HashMap map = new HashMap();
        map.put("data", otherVos);
        ajaxResult.put("rows", map);
        ajaxResult.put("code", HttpStatus.SUCCESS);
        ajaxResult.put("msg", "查询成功");
        ajaxResult.put("data", orderInfoMapper.selectOtherVo(vo));
        return ajaxResult;
    }

    /**
     * 查询对账数据报表
     *
     * @param vo
     * @return
     */
    public List<ReconciliationVo> selectReconciliationVo(ReconciliationVo vo) {
        return orderInfoMapper.selectReconciliationVo(vo);
    }

    public List<KuaDianVo> selectKuaDianList(ReconciliationVo vo) {
        return orderInfoMapper.selectKuaDianList(vo);
    }

    public ReconciliationVo selectReconciliationVoManCount(ReconciliationVo vo) {
        return orderInfoMapper.selectReconciliationVoManCount(vo);
    }

    public ReconciliationVo selectReconciliationVoItemCount(ReconciliationVo vo) {
        return orderInfoMapper.selectReconciliationVoItemCount(vo);
    }

    public ReconciliationVo selectReconciliationVoKuaDianShouRuAndZhiChu(ReconciliationVo vo) {
        return orderInfoMapper.selectReconciliationVoKuaDianShouRuAndZhiChu(vo);
    }

    /**
     * 统计客户购买的服务项目和套餐卡的相关数据
     *
     * @param name
     * @return
     */
    public List<BuyRecordNotUsed> selectNotUsedBuyRecord(BuyRecordNotUsed name) {
        return orderInfoMapper.selectNotUsedBuyRecord(name);
    }

    /**
     * 统计客户购买的服务项目和套餐卡的详情
     *
     * @param used
     * @return
     */
    public List<CustomerServiceBuyRecordVo> getNotUsedBuyRecordDetail(BuyRecordNotUsed used) {
        return orderInfoMapper.getNotUsedBuyRecordDetail(used);
    }

}
